import jwt
from django.db.models.expressions import result
from jwt import ExpiredSignatureError
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from user.models import UserModel
from utils.myjwt import jwtweb


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token=request.META.get("HTTP_AUTHORIZATION",None)
        if token:
            tokendata=token.split(" ")[1]
            try:
                result=jwtweb.checktoken(tokendata)
                #去表中查询数据
                user=UserModel.objects.get(id=result['id'])
                return (user,tokendata)
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('token过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed("token无效")
        else:
            raise AuthenticationFailed('Token is required.')
